let func = require("../utils/functions")
let mongodb = require("../utils/db.mongo")

module.exports = {

    'GET /apply/list': async function(ctx, next){
        let list,count,
        req = ctx.query,
        page = func.empty(req.page) ? 1 : parseInt(req.page),
        limit = func.empty(req.limit) ? 20 : parseInt(req.limit) ;
        var db_condition = {},
        mobile  = req.mobile,
        addtime = {};
        //查询条件
        if(!func.empty(req.mobile))   db_condition.mobile = mobile
        if(!func.empty(req.starttime)) addtime['$gt'] = parseInt(req.starttime)
        if(!func.empty(req.endtime))   addtime['$lt'] = parseInt(req.endtime)
        if(!func.empty(req.starttime) || !func.empty(req.endtime)) db_condition.addtime = addtime
        // console.log(db_condition)
        list = await mongodb.findLimit('apply',db_condition,page,limit)
        count = await mongodb.findLimitCount('apply',db_condition)
        return ctx.body = {"items":list,"total":count}
    },

    'POST /apply/add': async function(ctx, next){
        let req = ctx.request.body;
        var applier = {
            "name"          : req.name,
            "sex"           : req.sex,
            "age"           : req.age,
            "mobile"        : req.mobile,
            "qq"            : req.qq,
            "lottery_age"   : req.lottery_age,
            "lottery_adept" : req.lottery_adept,
            "lived"         : req.lived,
            "system"        : req.system,
            "addtime"       : new Date().getTime()
        }

        for(let k in applier) {  
            if(func.empty(applier[k])) return ctx.body = func.toJson('',400, k+'不能为空')
        } 
        mongodb.insert('apply', applier);
        return ctx.body = func.toJson('',200, '成功')
    }

}
